package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
public class SessionController {

    //设置cookie

    /***
     * response响应头，服务端发送到浏览器
     * @param response
     * @return
     */
    @GetMapping("/c1")
    public Result cookieDome(HttpServletResponse response){
        response.addCookie(new Cookie("namedome","lcw"));//设置Cookie/响应Cookie
        return Result.success();
    }

    /**
     * request 请求头浏览器向服务端发送请求
     * @param request
     * @return
     */
    @GetMapping("/c2")
    public Result cookieDome2(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("namedome")){
                System.out.println("namedome: "+cookie.getValue()); //输出name为login_username的cookie
            }
        }
        return Result.success();

    }

    /**
     * session
     */
    @GetMapping("/s1")
    public Result session1(HttpSession session){
        log.info("HttpSession-s1: {}", session.hashCode());
        session.setAttribute("loginUser", "lcw"); //往session中存储数据
        return Result.success();
    }

    @GetMapping("s2")
    public Result session2(HttpServletRequest request){
        HttpSession session = request.getSession();
        log.info("HttpSession-s2: {}", session.hashCode());
        Object loginUser = session.getAttribute("loginUser"); //从session中获取数据
        log.info("loginUser: {}", loginUser);
        return Result.success(loginUser);
    }


}
